<?php
namespace app\admin\controller;
use app\admin\service\CategoryService;
use clt\Tree;
use think\facade\Request;
use think\facade\Env;
class Category extends Base
{
    protected $dao, $categorys , $module;
    function initialize()
    {
        parent::initialize();
        foreach ((array)$this->module as $rw){
            if($rw['type']==1 && $rw['status']==1){
				$data['module'][$rw['id']] = $rw;
			}
        }
        $this->module=$data['module'];
        $this->assign($data);
        unset($data);
        $this->dao = db('category');
    }
    public function index()
    {
        $categoryService = new CategoryService();
        $list = $categoryService->getList(1, 100);

        $array = [];
        foreach ($list['data'] as $r) {
            $r['str_manage'] = '';
            $r['str_manage'] .= '<a class="blue" title="添加子栏目" href="' . url('Category/add', array('parentid' => $r['id'])) . '"> <i class="icon icon-plus"></i></a> | <a class="green" href="' . url('Category/edit', array('id' => $r['id'])) . '" title="修改"><i class="icon icon-pencil2"></i></a> | <a class="red" href="javascript:del(\'' . $r['id'] . '\')" title="删除"><i class="icon icon-bin"></i></a> ';
            $array[] = $r;
        }

        $str = "<tr><td class='visible-lg visible-md'>\$id</td>";
        $str .= "<td class='text-left'>\$spacer<a href='javascript:;' class='green' title='查看内容'>\$catname </a>&nbsp;</td>";

        $str .= "<td><input type='text' size='10' data-id='\$id' value='\$sort' class='layui-input list_order'></td><td>\$str_manage</td></tr>";
        $tree = new Tree ($array);
        $tree->icon = array('&nbsp;&nbsp;&nbsp;│  ', '&nbsp;&nbsp;&nbsp;├─ ', '&nbsp;&nbsp;&nbsp;└─ ');
        $tree->nbsp = '&nbsp;&nbsp;&nbsp;';
        $categorys = $tree->get_tree(0, $str);

        $this->assign('categorys', $categorys);
        $this->assign('title','栏目列表');
        return $this->fetch();

    }

    public function add(CategoryService $categoryService){
        $parentid =	input('param.parentid');

        //栏目选择列表
        $array = [];
        foreach($this->categorys as $r) {
            $array[] = $r;
        }
        $str  = "<option value='\$id' \$selected>\$spacer \$catname</option>";
        $tree = new Tree ($array);
        $categorys = $tree->get_tree(0, $str,$parentid);
        $this->assign('categorys', $categorys);
        //管理员权限组
        $this->assign('title','添加栏目');
        return $this->fetch();
    }

    public function insert(){
        $data = $this->request->except('file');
        $data['child'] = isset($param['child'])?1:0;

        $id = db('category')->insertGetId($data);
        if($id) {
            return ['msg' => '栏目添加成功!', 'code' => 1, 'url' => url('index')];
        }else{
            return ['msg' => '栏目添加失败!', 'code' => 0];
        }
    }

    public function edit(CategoryService $categoryService){
        $id = input('id');

        $data = $categoryService->getInfo($id);
        $data['imgUrl'] = imgUrl($data['image']);
        $parentid =	intval($data['parentid']);
        $result = $this->categorys;
        foreach($result as $r) {
            if($r['type']==1) continue;
            $r['selected'] = $r['id'] == $parentid ? 'selected' : '';
            $array[] = $r;
        }
        $str  = "<option value='\$id' \$selected>\$spacer \$catname</option>";
        $tree = new Tree ($array);
        $categorys = $tree->get_tree(0, $str,$parentid);


        $this->assign('categorys', $categorys);
        $this->assign('record', $data);
        $this->assign('title','编辑栏目');
        return $this->fetch();
    }
    public function catUpdate(){
        $data = $data = Request::except('file');
        $data['arrparentid'] = $this->get_arrparentid($data['id']);
        $data['child'] = isset($data['child']) ? '1' : '0';
        if (false !==db('category')->update($data)) {
            return ['msg' => '栏目修改成功!', 'code' => 1, 'url' => url('index')];
        }else{
            return ['msg' => '栏目修改失败!', 'code' => 0];
        }
    }


    public function repair() {
        @set_time_limit(500);
        $this->categorys = $categorys = array();
        $categorys =  db('category')->where("parentid=0")->order('sort ASC,id ASC')->select();
        $this->set_categorys($categorys);
        if(is_array($this->categorys)) {
            foreach($this->categorys as $id => $cat) {
                if($id == 0 || $cat['type']==1) continue;
                $this->categorys[$id]['arrparentid'] = $arrparentid = $this->get_arrparentid($id);
                $this->categorys[$id]['arrchildid'] = $arrchildid = $this->get_arrchildid($id);
                $this->categorys[$id]['parentdir'] = $parentdir = $this->get_parentdir($id);
                db('category')->update(array('parentdir'=>$parentdir,'arrparentid'=>$arrparentid,'arrchildid'=>$arrchildid,'id'=>$id));
            }
        }

    }
    public function set_categorys($categorys = array()) {
        if (is_array($categorys) && !empty($categorys)) {
            foreach ($categorys as $id => $c) {
                $this->categorys[$c['id']] = $c;
                $r = db('category')->where(array("parentid"=>$c['id']))->Order('sort ASC,id ASC')->select();
                $this->set_categorys($r);
            }
        }
        return true;
    }
    public function get_arrparentid($id, $arrparentid = '') {
        if(!is_array($this->categorys) || !isset($this->categorys[$id])) return false;
        $parentid = $this->categorys[$id]['parentid'];
        $arrparentid = $arrparentid ? $parentid.','.$arrparentid : $parentid;
        if($parentid) {
            $arrparentid = $this->get_arrparentid($parentid, $arrparentid);
        } else {
            $this->categorys[$id]['arrparentid'] = $arrparentid;
        }
        return $arrparentid;
    }
    public function get_arrchildid($id) {
        $arrchildid = $id;
        if(is_array($this->categorys)) {
            foreach($this->categorys as $catid => $cat) {
                if($cat['parentid'] && $id != $catid) {
                    $arrparentids = explode(',', $cat['arrparentid']);
                    if(in_array($id, $arrparentids)){
                        $arrchildid .= ','.$catid;
                    }
                }
            }
        }
        return $arrchildid;
    }
    public function get_parentdir($id) {
        if($this->categorys[$id]['parentid']==0){
            return '';
        }
        $arrparentid = $this->categorys[$id]['arrparentid'];
        unset($r);
        if ($arrparentid) {
            $arrparentid = explode(',', $arrparentid);
            $arrcatdir = array();
            foreach($arrparentid as $pid) {
                if($pid==0) continue;
                $arrcatdir[] = $this->categorys[$pid]['catdir'];
            }
            return implode('/', $arrcatdir).'/';
        }
    }


    public function del() {
        $catid = input('param.id');
        $scount = $this->dao->where(array('parentid'=>$catid))->count();

        if($scount){
            return ['msg' => '请先删除其子栏目', 'code' => 0, 'url' => url('index')];
        }

        db('category')->where('id', $catid)->delete();
        savecache('Category');
        cache('cate', NULL);
        return ['msg' => '栏目删除成功!', 'code' => 1, 'url' => url('index')];
    }

    public function cOrder(){
        $data = input('post.');
        $this->dao->update($data);
        $result = ['msg' => '排序成功！', 'code' => 1,'url'=>url('index')];
        savecache('Category');
        cache('cate', NULL);
        return $result;
    }
}